package com.augurit.common.common.http.kt.client

import com.augurit.common.common.http.kt.interceptor.DrainageGlobalHttpHandler
import com.augurit.common.common.http.kt.interceptor.HttpHandlerInterceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import java.util.concurrent.TimeUnit

/**
 *  author : yanghaozhang
 *  date : 2022/5/3 16:28
 *  description :
 */
open class BaseRetrofitFactory private constructor() : IRetrofitFactory {

    companion object {
        const val DEFAULT_MILLISECONDS = 60000 //默认的超时时间

        const val DEFAULT_RETRY_COUNT = 3 //默认重试次数

        const val DEFAULT_RETRY_INCREASEDELAY = 0 //默认重试叠加时间

        const val DEFAULT_RETRY_DELAY = 500L //默认重试延时

        var instance = BaseRetrofitFactory()

    }

    private var retrofitMap = mutableMapOf<String, Retrofit>()

    @Synchronized
    override fun getRetrofit(baseUrl: String): Retrofit {
        val retrofit = retrofitMap[baseUrl] ?: createRetrofit(baseUrl).also {
            retrofitMap[baseUrl] = it
        }
        return retrofit
    }

    fun createRetrofit(baseUrl: String): Retrofit {
        return Retrofit.Builder()
            .baseUrl(baseUrl)
//            .addConverterFactory(ScalarsConverterFactory.create())
//            .addConverterFactory(GsonConverterFactory.create())
            .client(getOkHttpClient())
            .build()
    }

    fun getOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .addInterceptor(HttpHandlerInterceptor(DrainageGlobalHttpHandler()))
//            .addInterceptor(HeaderInterceptor())
//            .addInterceptor(LoggingInterceptor())
//            .addInterceptor(RetryInterceptor(DEFAULT_RETRY_COUNT, DEFAULT_RETRY_DELAY))
            .connectTimeout(DEFAULT_MILLISECONDS.toLong(), TimeUnit.MILLISECONDS)
            .readTimeout(DEFAULT_MILLISECONDS.toLong(), TimeUnit.MILLISECONDS)
            .writeTimeout(DEFAULT_MILLISECONDS.toLong(), TimeUnit.MILLISECONDS)
            .build()
    }
}